<?php
/**
 * Created by PhpStorm.
 * User: seven
 * Date: 2015/12/22
 * Time: 18:17
 */

namespace Album\Model;


use Zend\Db\TableGateway\TableGateway;

class AlbumTable
{
    protected $tableGateWay;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateWay = $tableGateway;
    }

    public function fetchAll()
    {
        $resultSet = $this->tableGateWay->select();
        return $resultSet;
    }

    public function getAlbum($id)
    {
        $id     = (int)$id;
        $rowset = $this->tableGateWay->select(['id' => $id]);
        $row    = $rowset->current();
        if (!$row)
            throw new \Exception("Could not find row $id");
        return $row;
    }

    public function saveAlbum(Album $album)
    {
        $data = [
            'artist' => $album->artist,
            'title'  => $album->title
        ];
        $id   = (int)$album->id;
        if ($id == 0) {
            $this->tableGateWay->insert($data);
        } else {
            if ($this->getAlbum($id)) {
                $this->tableGateWay->update($data, ['id' => $id]);
            } else {
                throw new \Exception('Album id does not exist');
            }
        }
    }

    public function deleteAlbum($id)
    {
        $this->tableGateWay->delete(['id' => (int)$id]);
    }

}